<!DOCTYPE html>
<html>
<head>
    <title>FastLED Pure JavaScript Architecture Debug Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .debug-section { 
            margin: 20px 0; 
            padding: 10px; 
            border: 1px solid #ccc; 
            background-color: #f9f9f9;
        }
        #console-output {
            width: 100%;
            height: 400px;
            border: 1px solid #000;
            background-color: #000;
            color: #00ff00;
            font-family: monospace;
            font-size: 12px;
            overflow-y: scroll;
            padding: 10px;
        }
        button {
            margin: 5px;
            padding: 10px 20px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <h1>FastLED Pure JavaScript Architecture Debug Test</h1>
    
    <div class="debug-section">
        <h2>Module Loading Status</h2>
        <div id="module-status">Loading...</div>
    </div>
    
    <div class="debug-section">
        <h2>Debug Controls</h2>
        <button onclick="testModuleLoading()">Test Module Loading</button>
        <button onclick="testCallbackFunctions()">Test Callback Functions</button>
        <button onclick="testAsyncController()">Test Async Controller</button>
        <button onclick="clearConsole()">Clear Console</button>
    </div>
    
    <div class="debug-section">
        <h2>Debug Console Output</h2>
        <div id="console-output"></div>
    </div>

    <script type="module">
        // Capture console output
        const consoleOutput = document.getElementById('console-output');
        const originalLog = console.log;
        const originalError = console.error;
        const originalWarn = console.warn;
        
        function addToConsole(type, ...args) {
            const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
            const message = args.map(arg => {
                if (typeof arg === 'object') {
                    try {
                        return JSON.stringify(arg, null, 2);
                    } catch (e) {
                        return String(arg);
                    }
                }
                return String(arg);
            }).join(' ');
            
            const line = document.createElement('div');
            line.style.color = type === 'error' ? '#ff4444' : 
                              type === 'warn' ? '#ffaa00' : '#00ff00';
            line.textContent = `[${timestamp}] ${type.toUpperCase()}: ${message}`;
            consoleOutput.appendChild(line);
            consoleOutput.scrollTop = consoleOutput.scrollHeight;
        }
        
        console.log = (...args) => {
            originalLog(...args);
            addToConsole('log', ...args);
        };
        
        console.error = (...args) => {
            originalError(...args);
            addToConsole('error', ...args);
        };
        
        console.warn = (...args) => {
            originalWarn(...args);
            addToConsole('warn', ...args);
        };
        
        // Test functions
        window.clearConsole = function() {
            consoleOutput.innerHTML = '';
        };
        
        window.testModuleLoading = async function() {
            console.log('=== Testing Module Loading ===');
            
            try {
                // Try to import debug logger
                const { FASTLED_DEBUG_LOG } = await import('./src/platforms/wasm/compiler/fastled_debug_logger.js');
                console.log('✓ Debug logger imported successfully');
                FASTLED_DEBUG_LOG('TEST', 'Debug logger working correctly');
                
                // Try to import async controller
                const { FastLEDAsyncController } = await import('./src/platforms/wasm/compiler/fastled_async_controller.js');
                console.log('✓ Async controller imported successfully');
                
                // Try to import callbacks
                await import('./src/platforms/wasm/compiler/fastled_callbacks.js');
                console.log('✓ Callbacks imported successfully');
                
                // Try to import events
                const { fastLEDEvents } = await import('./src/platforms/wasm/compiler/fastled_events.js');
                console.log('✓ Events imported successfully');
                
                document.getElementById('module-status').innerHTML = '✅ All modules loaded successfully';
                
            } catch (error) {
                console.error('❌ Module loading failed:', error);
                document.getElementById('module-status').innerHTML = '❌ Module loading failed: ' + error.message;
            }
        };
        
        window.testCallbackFunctions = function() {
            console.log('=== Testing Callback Functions ===');
            
            const callbacks = [
                'FastLED_onFrame',
                'FastLED_processUiUpdates', 
                'FastLED_onStripUpdate',
                'FastLED_onStripAdded',
                'FastLED_onUiElementsAdded',
                'FastLED_onError'
            ];
            
            callbacks.forEach(callbackName => {
                const callback = globalThis[callbackName];
                if (typeof callback === 'function') {
                    console.log(`✓ ${callbackName} is available and is a function`);
                } else {
                    console.error(`❌ ${callbackName} is NOT available or not a function (type: ${typeof callback})`);
                }
            });
        };
        
        window.testAsyncController = function() {
            console.log('=== Testing Async Controller Creation ===');
            
            // Create a mock WASM module
            const mockModule = {
                cwrap: function(funcName, returnType, argTypes) {
                    console.log(`Mock cwrap called for: ${funcName}`);
                    return function(...args) {
                        console.log(`Mock function ${funcName} called with args:`, args);
                        return returnType === 'number' ? 0 : null;
                    };
                },
                _malloc: function(size) {
                    console.log(`Mock _malloc called with size: ${size}`);
                    return 12345; // Mock pointer
                },
                _free: function(ptr) {
                    console.log(`Mock _free called with pointer: ${ptr}`);
                },
                getValue: function(ptr, type) {
                    console.log(`Mock getValue called with pointer: ${ptr}, type: ${type}`);
                    return 0;
                },
                UTF8ToString: function(ptr, length) {
                    console.log(`Mock UTF8ToString called with pointer: ${ptr}, length: ${length}`);
                    return '[]'; // Mock empty JSON array
                }
            };
            
            try {
                import('./src/platforms/wasm/compiler/fastled_async_controller.js').then(({ FastLEDAsyncController }) => {
                    console.log('Creating FastLEDAsyncController with mock module...');
                    const controller = new FastLEDAsyncController(mockModule, 60);
                    console.log('✓ FastLEDAsyncController created successfully');
                    
                    // Test setup
                    console.log('Testing controller setup...');
                    controller.setup().then(() => {
                        console.log('✓ Controller setup completed');
                        
                        // Test start
                        console.log('Testing controller start...');
                        controller.start();
                        console.log('✓ Controller started');
                        
                        // Stop after a few seconds
                        setTimeout(() => {
                            controller.stop();
                            console.log('✓ Controller stopped');
                        }, 3000);
                        
                    }).catch(error => {
                        console.error('❌ Controller setup failed:', error);
                    });
                    
                }).catch(error => {
                    console.error('❌ Failed to import FastLEDAsyncController:', error);
                });
                
            } catch (error) {
                console.error('❌ Test async controller failed:', error);
            }
        };
        
        // Auto-run initial tests
        console.log('FastLED Pure JavaScript Architecture Debug Test Starting...');
        setTimeout(testModuleLoading, 100);
    </script>
</body>
</html> 
